package com.canyou.support;

import com.canyou.constants.CommonConstants;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.format.Formatter;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.Locale;

/**
 * 格式化金额
 *
 * @author fy
 * @date 20/03/20 16:12
 */
@Component
public class MoneyFormatter implements Formatter<Money> {

    private static final String CURRENCY_UNIT = CommonConstants.CURRENCY_UNIT;

    /**
     * 处理 CNY 10.00 / 10.00 形式的字符串
     *
     * @param text
     * @param locale
     * @return
     * @throws ParseException
     */
    @Override
    public Money parse(String text, Locale locale) throws ParseException {
        if (NumberUtils.isParsable(text)) {
            // 处理10.00格式的金额数值
            return Money.of(CurrencyUnit.of(CURRENCY_UNIT), NumberUtils.createBigDecimal(text));
        } else if (StringUtils.isNotEmpty(text)) {
            // 处理CNY 10.00格式的金额数值
            String moneyConcatStr = " ";
            int moneyArrLen = 2;
            // 分割货币类型和货币值构造出实际money值对象
            String[] split = StringUtils.split(text, moneyConcatStr);
            if (split != null && split.length == moneyArrLen && NumberUtils.isParsable(split[1])) {
                return Money.of(CurrencyUnit.of(split[0]), NumberUtils.createBigDecimal(split[1]));
            } else {
                throw new ParseException(text, 0);
            }
        }
        throw new ParseException(text, 0);
    }

    /**
     * 打印金额
     *
     * @param money
     * @param locale
     * @return
     */
    @Override
    public String print(Money money, Locale locale) {
        if (money == null) {
            return null;
        }
        return money.getCurrencyUnit().getCode() + " " + money.getAmount();
    }

}
